<template>
  <div class="app-container add-page">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="Particpact" name="Particpact">
        <el-form ref="info" class="container-fluid setting" style="overflow: hidden;height: calc(100vh - 150px);position: relative;" :model="info" :rules="rules">
            <div class="_container " style="height:calc(100% - 70px);overflow-y: auto;overflow-x: hidden;">


          <el-row class="filter-container" align="bottom">
            <el-col :sm="12">
              <el-form-item prop="status">
                <div class="ul-input">
                  <label for="">
                    status:
                  </label>
                  <el-select
                    v-model="info.status"
                    placeholder="请选择"
                    @change="changeStatus"
                  >
                    <el-option
                      v-for="item in optStatus"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :sm="12" style="text-align:right">
              <el-form-item prop="suspendReason">
              <div class="ul-input">
                  <label for="">
                    Suspend reason:
                  </label>
                  <el-select
                    v-model="info.suspendReason"
                    placeholder="Please select suspend reason"
                    @change="changeReason"
                  >
                    <el-option
                      v-for="item in optReason"
                      :key="item.value"
                      :label="item.typeName"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :sm="12">

              <el-form-item prop="coaches">
                <input v-show="false" v-model="info.coaches" type="text">
                <h3 class="title">Coaches / Helpers</h3>
              </el-form-item>
              <div class="ul-input">
                <!--
                  <el-autocomplete
                v-if="!inputReadonly"
                v-model="Athlete.name"
                :fetch-suggestions="queryAthleteSearchAsync"
                :clearable="false"
                placeholder="Athlete name"
                :readonly="inputReadonly"
                @select="athleteshandleSelect"
                @blur="athleteshandleBlur"
              /> -->
                <el-autocomplete
                  v-model="followUpData.name"
                  :fetch-suggestions="querySearchAsync"
                  :clearable="true"
                  placeholder="Coaches / Helpers"
                  @select="handleSelect"
                />

                <!-- <el-input  class="filter-item"></el-input> -->
                <button type="button" class="el-button el-button--success" @click="addFollowUp(followUpData.name, followUpData.userId)"><span>Add</span></button>
              </div>
              <!--  v-loading="listLoading" -->

              <el-table
                ref="table"
                height="260px"
                :data="followUpData.list"
                element-loading-text="Loading"
                border
                fit
                highlight-current-row
                stripe
                @selection-change="handleSelectionChange"
              >
                <el-table-column min-width="150" label="Coach"  sortable="custom">
                  <template slot-scope="scope">
                  <template v-if="scope.row.name" >
                    {{scope.row.name}}
                  </template>
                  <template   v-else>
                  {{scope.row | FilterName(false,' ',"(" + scope.row.hkId + ")")}}
                    </template>
                  </template>
                </el-table-column>
                <el-table-column label="Title" min-width="170" align="center" prop="rateCardTitle" sortable="custom">
                  <template slot-scope="scope">

                    <el-select v-model="scope.row.rateCardTitle"
                    :fi='()=>(!scope.row.rateCardTitle?$set(scope.row,"rateCardTitle",""):"")'>
                     <el-option :key='i' v-for='(list ,i) in getTrainInfo.titleNameList'
                     :value='list.id' :label="list.titleName">

                     </el-option>

                    </el-select>

                  </template>
                </el-table-column>
                <el-table-column label="Master Coach" width="130"  align="center" prop="masterCoach" sortable="custom">
                  <template slot-scope="scope">
                    <el-checkbox :true-label='1' :false-label='0' v-model="scope.row.masterCoach" />
                  </template>
                </el-table-column>
                <el-table-column label="Roll Call" width="90" prop="rollCall" sortable="custom">
                  <template slot-scope="scope">
                    <div class="t-center">
                      <el-checkbox :true-label='1' :false-label='0' v-model="scope.row.rollCall" />
                     </div>
                  </template>
                </el-table-column>
                <el-table-column label="" v-if='followUpData.list.length' width="50" >
                  <template slot-scope="scope">
                    <img v-if="scope.row" src="../../assets/images/del.svg" class="btn-icon" style="vertical-align: middle;" @click="delFollowUp(scope.$index)" />

                  </template>
                </el-table-column>

              </el-table>
              </el-form-item >
            </el-col>
            <!--  -->
            <el-col :sm="12">
              <el-form-item prop="athletes">
                <input v-show="false" v-model="info.athletes" type="text">
                <h3 class="title">{{ Athlete.title }}</h3>
              </el-form-item>
              <div class="ul-input">
                <el-autocomplete

                  v-model="athleteData.name"
                  :fetch-suggestions="queryAthleteSearchAsync"
                  :clearable="false"
                  placeholder="Athlete name"
                  @select="athleteshandleSelect"
                  @blur="athleteshandleBlur"
                />
                <!-- <el-select @change='getList("Athlete",Coaches.value)' v-model="Athlete.value"  class="set-input" filterable placeholder="请选择">
                  <el-option
                    v-for="item in Athlete.list"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select> -->
                <!-- <input v-model="" placeholder="Text" > -->

                <button type="button" class="el-button el-button--success" @click="addFollowUp(athleteData.name, athleteData.userId,'athleteData')"><span>Add</span></button>
              </div>
              <div class="set-table">
                <div :key='i' v-for="(listItem, i) in athleteData.list" v-if="listItem.isDelete !== 1" class="set-tr">
                  <template v-if="listItem.name">
                    {{listItem.name}}
                  </template>
                  <template v-else>
                  {{listItem | FilterName(null,' ','(' + listItem.hkId + ')')}}
                    </template>
                  <div>
                    <img
                      v-if="listItem.isUse !== 1"
                      src="../../assets/images/del2.svg"
                      class="btn-icon"
                      @click="delFollowUp(i,'athleteData')"
                    >
                  </div>
                </div>
              </div>

            </el-col>
          </el-row>

                   </div>
                   <el-form-item class="btm-btn-groups" style="margin: 15px 0;text-align: center;">
                     <el-button  type="success" size="medium" @click="$router.push({path:'/trainSchedule/add?page=Course',query:{
                       actionInstruct:$route.query.actionInstruct,
                       pageNum:$route.query.pageNum,
                       size:$route.query.size,
                       id:$route.query.id
                     }}
                     )">Back</el-button>
                     <!--<el-button v-if="info.status !='PUBLISH' && this.$route.query.id && userType === 'ADMIN' && (pageType === 'SportMedicine' || pageType === 'SportScience' || (pageType === 'Medication' && activeName === 'mn2'))" type="success" size="medium" @click="onSubmit('info', 'publish')">Publish</el-button>
                   <el-button v-if="this.$route.query.id && userType === 'ADMIN'" v-print="'#print'" type="success" size="medium">Print</el-button>
                   <el-button v-if="info.modify && this.$route.query.id" type="success" size="medium" @click="onSubmit('info', 'save')">Save</el-button> -->
                     <el-button type="success" size="medium" @click="onSubmit('info')">Apply</el-button>
                   </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
    import store from '@/store'
    //import { getInterList } from '@/api/home'
    import { queryAthletesList, queryUserList } from '@/api/setting'
    import { getTrainInfo, asyncGet,updateInfo} from '@/api/trainSchedule'

    export default {
        filters: {
            statusFilter(status) {
                const statusMap = {
                    published: 'success',
                    draft: 'gray',
                    deleted: 'danger'
                }
                return statusMap[status]
            }
        },
        data() {
          //4203 禪道
          let validateCoachesFn=(rule, value, callback)=>{
                      if(this.isChecked){
                       callback();
                    }else{
                      callback(new Error('Select a master coach or coach on at least one of the coaches'));
                    }
                    callback();
          }
            return {
             nowDate: new Date(),
                Coaches: {
                  title: 'Athlete',
                    typeCode: 'COACH',
                    value: '',
                    list: []
                },
                getTrainInfo,
                Athlete: {
                    title: 'Athlete',
                    typeCode: 'ATHLETE',
                    value: '',
                    list: []
                },
                athleteData: {
                    name: '', id: '', list: []
                },
                followUpData: {
                    name: '', id: '',
                     rollCall: 0,
                     masterCoach: 0,
                     rateCardTitle: '', list: []
                },
              optStatus: [{
                       value: 'Active',
                       label: 'Active'
                     }, {
                       value: 'Completed',
                       label: 'Completed'
                     }, {
                       value: 'Suspended',
                       label: 'Suspended'
                     }],
              optReason: [],
                     info: {
                        status: '',
                        suspendReason: '',
                        coaches: [],
                        athletes: []
                     },
              pickerOptions: {
                      },
                      value1: '',
                      value2: '',

                helpersList: [],
                athletesList: [],
                rules: {
                   status: [
                  { required: true, trigger: 'change', message: 'please edit/add  in status' }
                  // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                  ],
                  suspendReason: [
                  { required: false, trigger: 'change', message: 'please edit/add  in suspendReason' }
                  // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                  ],
                  coaches: [
                       { required: false, message: 'please edit/add in coaches' },
                       {validator:validateCoachesFn}
                  ],
                  athletes: [
                       { required: false, message: 'please edit/add  in athletes' }

                  ]
                },
                list: [],
                listQuery: {
                    page: 1,
                    limit: 25,
                    total: 0,
                    sorting: '',
                    column: '',
                    startDate: '',
                    endDate: ''
                },
                sportScienceList: {
                    list: [],
                    listQuery: {
                        page: 1,
                        limit: 25
                    }
                },
                listLoading: true,
                activeName: 'Particpact',
                link: '/trainSchedule/add',
                summaryList: [],
                listIndexs: [],
                minWindths: [],
                userType: store.getters.userType
            }
        },
         computed: {

                },
        watch: {
           $route: {
                handler: function(route) {
                    this.target = route.query && route.query.target
                },
                immediate: true
            },
            ['info.status'](statu){
             this.rules.suspendReason[0].required =  statu === 'Suspended'
            }
            // activeName(val) {
            //     this.$router.push(`${this.$route.path}?tab=${val}`)
            // }
        },
        mounted(e) {
        },
        created() {
            const query = this.$route.query
            if (query.tab) {
                this.activeName = query.tab || 'Particpact'
            }
            this.fetchData()
        },
        methods: {

          changeStatus(e) {
            //debugger
          },
          changeReason(e) {
            //debugger
          },
       querySearchAsync(queryString, cb) {
                if (queryString === '') {
                    cb([])
                    return false
                }
                 asyncGet('/setting/query/coach','get',{ name: queryString }).then(response => {
                    // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
                    var results = []; var data = response.result
                    for (var i in data) {
                        results.push({
                            value:this.FilterName(data[i],null,' ','(' + data[i].hkId + ')'),
                            name: this.FilterName(data[i],null,' ','(' + data[i].hkId + ')'),
                            rollCall: 0,
                            masterCoach: 0,
                            rateCardTitle: '',
                            userId: data[i].userId,
                            hkId:data[i].hkId
                        })
                    }
                    clearTimeout(this.timeout)
                    this.timeout = setTimeout(() => {
                        cb(results)
                    }, 200 * Math.random())
                })
            },
            queryAthleteSearchAsync(queryString, cb) {
                if (queryString === '') {
                    cb([])
                    return false
                }

                queryAthletesList({ name: queryString }).then(response => {
                    // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
                    var results = []; var data = response.result
                    for (var i in data) {
                        results.push({
                            value:this.FilterName(data[i],null,' ','(' + data[i].hkId + ')'),
                            name: this.FilterName(data[i],null,' ','(' + data[i].hkId + ')'),
                            userId: data[i].userId,
                            hkId:data[i].hkId
                        })
                    }
                    clearTimeout(this.timeout)
                    this.timeout = setTimeout(() => {
                        cb(results)
                    }, 200 * Math.random())
                })
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
                }
            },
            handleSelect(item) {
              //debugger
                this.followUpData.name = item.name
                this.followUpData.userId = item.userId
                this.followUpData.id = item.id
                this.followUpData.hkId = item.hkId
              console.log(item)
            },

            athleteshandleSelect(item) {
                this.athleteData.name = item.name
                this.athleteData.userId = item.userId
                this.athleteData.hkId = item.hkId
                this.info.memberId = item.id
            },
            athleteshandleBlur(item) {
                // const that = this
                // setTimeout(function() {
                //   getGeneralInfoList({ athleteId: that.info.memberId }).then(response => {
                //       const data = response.result
                //       const name = data.general.lastName + ' ' + data.general.firstName
                //       if (name !== that.athleteData.name) {
                //           that.athleteData.name = name
                //       }
                //   })
                // }, 1000)
            },
            addFollowUp(name, id, type) {
                if (!name && !id) {
                    this.$message({
                        type: 'error',
                        message: 'Please select users'
                    })
                    return false
                }
                if (name && id) {
                  if (type === 'athleteData') {
                      const list = this.athleteData.list
                      for (var i in list) {
                        if (list[i].userId === id) {
                          this.athleteData.name = ''
                          this.athleteData.userId = ''
                          return false
                        }
                      }
                      list.push({ name: name, userId: id })
                      this.athleteData.name = ''
                      this.athleteData.userId = ''
                  } else {
                      const list = this.followUpData.list
                      for (var i in list) {
                       if (list[i].userId === id) {
                         this.followUpData.name = ''
                         this.followUpData.userId = ''

                         this.followUpData.hkId = ''
                        this.followUpData.rollCall = ''
                        this.followUpData.masterCoach = ''
                        this.followUpData.rateCardTitle = ''
                         return false
                       }
                      }
                      list.push({ name: name, userId: id, rateCardTitle: '', rollCall: 0, masterCoach: 0 })
                      this.followUpData.rollCall = ''
                      this.followUpData.rateCardTitle = ''
                      this.followUpData.masterCoach = ''
                      this.followUpData.name = ''
                      this.followUpData.userId = ''
                  }
                }
            },
            delFollowUp(key, type) {
                if (type === 'athleteData') {
                    const list = this.athleteData.list
                    list.splice(key, 1)
                } else {
                    const list = this.followUpData.list
                    list.splice(key, 1)
                }
            },
      async getLesson_many() {
        const { actionInstruct, lessonIds } = this.$route.query
        const res = await asyncGet('/course/manager/obtain/lesson_many', 'post', null, { lessonIds, actionInstruct })
        const { result: suspendReason } = await asyncGet('/setting/type/query_code', 'get', { code: 'SUSPEND_REASSON' })
        if (res.status === 0) {
                console.log('coachList,athleteList', res.result)
                this.getTrainInfo = res.result
                this.followUpData.list  = res.result.coachList
                this.athleteData.list = res.result.athleteList
                this.info.status = res.result.lesson.status
                //debugger
                this.optReason = suspendReason
                this.info.suspendReason =  res.result.lesson.suspendReason?res.result.lesson.suspendReason:''
                        }
      },
      onSubmit() {
            const { actionInstruct, lessonIds ,pageNum,size,id} = this.$route.query
            let { suspendReason, status, coaches, athletes } = this.info
            coaches =[]
            //debugger
            this.isChecked = false
                 debugger
            this.followUpData.list.map((coa, o) => {

              let { masterCoach,[coa.rateCardTitle?'rateCardTitle':'rateCard']:rateCardTitle, rollCall, userId } = coa
              if(!this.isChecked){
                this.isChecked = masterCoach || rateCardTitle
              }
              coaches.push({ masterCoach, rateCardTitle, rollCall,  userId })
            })

            var that = this
            this.athleteData.list.map((ath, l) => {
              athletes.push(ath.userId ? ath.userId : ath.id)
            })
            console.log('loop',coaches,athletes)
             debugger
            coaches = JSON.stringify(coaches)
            athletes = JSON.stringify(athletes)

            this.$refs['info'].validate(async(valid) => {
                   console.log('valid', valid)
                  if (valid) {
                     const res = await asyncGet('course/manager/update/lesson_many', 'post', null, { status, suspendReason, lessonIds, actionInstruct, athletes, coachs:coaches })

                      if (res.status === 0) {
                        // updateInfo('course', { actionInstruct }).then((res) => {
                        //   if (res.status === 0) {
                        //          that.$message.success(res.msg)
                        //          that.$router.push('/trainSchedule?tab=' + that.activeName)
                                 // that.$router.push('/trainSchedule?tab=Course')
                                 that.$router.push({path:'/trainSchedule/add?page=Course',query:{
                                   actionInstruct,
                                   pageNum,
                                   size,
                                   id
                                 }})
                        //   }
                        // })
                      that.$message({
                         type: res.status ? 'warning' : 'success',
                         message: res.msg
                       })
                      }

                  } else {
                    console.log('error submit!!')
                    return false
                  }
                })
      },
      fetchData() {
             var name = 'Helpers'
              this.getLesson_many()
              //debugger
            },

            minWidth(i, text) {
                let w = 100
                if (text.length >= 10) {
                     w = 130
                } else if (text.length < 5 && text !== '') {
                     w = 50
                } else {
                     w = 100
                }
                // const w = text.length >= 10 ? 130 : 100
                console.log(text, text.length)
                return w
            },
            sportMedicineFormatLink(row, column) {
                return row.row.id = 1
            },

            handleClick(tab, event) {
                this.listLoading = true
                this.fetchData()
                this.listQuery.keyword = ''
            },
            handleFilter() {
                this.fetchData()
            },
            change_time(e) {
              console.log('333', e)
              e.pickerVisible = true
            },
             onBulkSubmit(row) {

              },
        toggleSelection(rows) {
        if (rows) {
            rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
        })
        } else {
            this.$refs.multipleTable.clearSelection()
        }
        },
        handleSelectionChange(val) {
          this.multipleSelection = val
        }
        }
    }
</script>
<style lang='scss' scope>
 .closeSoild{

     border-radius: 50%;
     display: bock;
     background: rgba(0,0,0,.5);
     padding:2px;
     color:#fff;
 }
</style>
